package org.dw.concessionaria.DAO;

//ir nas propriedades do projeto, Java Build Path e adicionar o jar do postgresql

import java.sql.Connection;
import java.sql.DriverManager;

public class ConnectionDAO {
	private Connection con=null;
	private static int clients=0;
	static private ConnectionDAO instance=null;
	private ConnectionDAO() { init(); }
	static synchronized public ConnectionDAO getInstance() {
		if (instance == null) {
			instance = new ConnectionDAO();
		}
		return instance;
	}
	
	private void init() {
		try {
			Class.forName("org.postgresql.Driver");
			con = DriverManager.getConnection("jdbc:postgresql://localhost/concessionaria","concessionaria","admin");
		} catch(Exception e){System.out.println(e.getMessage());};
	}
	public synchronized void devolveConnection(Connection con) {
		if (this.con==con) {
			clients--;
			notify();
		}
	}
	
	public synchronized Connection getConnection() {
		if(clients>0) {
			try {
				wait(5000);
			}
			catch (InterruptedException e) {};
			if(clients>0) return null;
		}
		clients ++;
		return con;
	}

}
